<template>
  <view class="page-container">
    <!-- 自定义导航栏 -->
    <CustomNavBar 
      title="日记详情" 
      :show-back="true"
      @rightClick="showActionModal = true"
    >
      <template #right>
        <uni-icons type="more" size="20" color="#333"></uni-icons>
      </template>
    </CustomNavBar>
    
    <!-- 页面内容 -->
    <view class="page-content" :style="{ paddingTop: navBarHeight + 'px' }" v-if="diary">
      <scroll-view scroll-y class="detail-scroll">
        <!-- 日记头部 -->
        <view class="diary-header">
          <text class="diary-title">{{ diary.title }}</text>
          <view class="diary-meta">
            <text class="meta-date">{{ formatDate(diary.diaryDate) }}</text>
            <text class="meta-time">{{ formatTime(diary.createdAt) }}</text>
          </view>
        </view>
        
        <!-- 日记信息栏 -->
        <view class="diary-info" v-if="diary.weather || diary.mood">
          <view class="info-item" v-if="diary.weather">
            <uni-icons type="cloud" size="18" color="#666"></uni-icons>
            <text class="info-text">{{ diary.weather }}</text>
          </view>
          <view class="info-item" v-if="diary.mood">
            <text class="mood-emoji">{{ getMoodEmoji(diary.mood) }}</text>
            <text class="info-text">{{ diary.mood }}</text>
          </view>
        </view>
        
        <!-- 日记图片 -->
        <view class="diary-images" v-if="diary.images && diary.images.length > 0">
          <view class="images-container">
            <image 
              v-for="(image, index) in diary.images" 
              :key="index"
              :src="image.url" 
              mode="widthFix"
              class="diary-image"
              @click="previewImage(index)"
              @load="onImageLoad"
              @error="onImageError"
            ></image>
          </view>
        </view>
        
        <!-- 日记内容 -->
        <view class="diary-content">
          <rich-text :nodes="formattedContent" class="content-text"></rich-text>
        </view>
        
        <!-- 日记标签 -->
        <view class="diary-tags" v-if="diary.category || (diary.tags && diary.tags.length > 0)">
          <view class="tags-container">
            <!-- 分类 -->
            <view class="tag category-tag" v-if="diary.category" :style="{ backgroundColor: diary.category.color + '20', color: diary.category.color }">
              <text class="tag-text">{{ diary.category.name }}</text>
            </view>
            
            <!-- 标签 -->
            <view 
              class="tag normal-tag" 
              v-for="tag in diary.tags" 
              :key="tag.id"
              :style="{ backgroundColor: tag.color + '20', color: tag.color }"
            >
              <text class="tag-text">{{ tag.name }}</text>
            </view>
          </view>
        </view>
        
        <!-- 日记统计 -->
        <view class="diary-stats">
          <view class="stats-item">
            <uni-icons type="compose" size="16" color="#999"></uni-icons>
            <text class="stats-text">{{ wordCount }} 字</text>
          </view>
          <view class="stats-item">
            <uni-icons type="calendar" size="16" color="#999"></uni-icons>
            <text class="stats-text">创建于 {{ formatDateTime(diary.createdAt) }}</text>
          </view>
          <view class="stats-item" v-if="diary.updatedAt !== diary.createdAt">
            <uni-icons type="refresh" size="16" color="#999"></uni-icons>
            <text class="stats-text">更新于 {{ formatDateTime(diary.updatedAt) }}</text>
          </view>
        </view>
        
        <!-- 操作按钮 -->
        <view class="action-buttons">
          <button class="action-btn edit-btn" @click="editDiary">
            <uni-icons type="compose" size="18" color="#1890ff"></uni-icons>
            <text class="btn-text">编辑</text>
          </button>
          <button class="action-btn share-btn" @click="shareDiary">
            <uni-icons type="redo" size="18" color="#52c41a"></uni-icons>
            <text class="btn-text">分享</text>
          </button>
        </view>
      </scroll-view>
    </view>
    
    <!-- 空状态 -->
    <EmptyState 
      v-if="!diary && !loading" 
      type="error" 
      title="日记不存在"
      description="该日记可能已被删除或您没有访问权限"
      button-text="返回列表"
      @buttonClick="goBack"
    />
    
    <!-- 日记操作菜单 -->
    <DiaryActionModal
      v-model:show="showActionModal"
      :diary="diary"
      @edit="editDiary"
      @delete="deleteDiary"
      @share="shareDiary"
    />
    
    <!-- 加载组件 -->
    <LoadingComponent :visible="loading" text="加载中..." />
  </view>
</template>

<script>
import { useDiaryStore } from '@/store/diary'
import { useUserStore } from '@/store/user'
import { getDiaryDetailAPI, deleteDiaryAPI } from '@/api/diary'
import { formatDate, formatDateTime } from '@/utils/index'
import CustomNavBar from '@/components/CustomNavBar.vue'
import EmptyState from '@/components/EmptyState.vue'
import LoadingComponent from '@/components/LoadingComponent.vue'

export default {
  name: 'DiaryDetailPage',
  components: {
    CustomNavBar,
    EmptyState,
    LoadingComponent
  },
  setup() {
    const diaryStore = useDiaryStore()
    const userStore = useUserStore()
    
    return {
      diaryStore,
      userStore,
      formatDate,
      formatDateTime
    }
  },
  data() {
    return {
      navBarHeight: 88,
      diaryId: null,
      diary: null,
      loading: false,
      showActionModal: false,
      
      // 心情表情映射
      moodEmojis: {
        '开心': '😊',
        '平静': '😌',
        '兴奋': '🤩',
        '难过': '😢',
        '愤怒': '😠',
        '焦虑': '😰',
        '疲惫': '😴',
        '感动': '🥺'
      }
    }
  },
  computed: {
    formattedContent() {
      if (!this.diary?.content) return ''
      
      // 将换行符转换为 <br> 标签
      return this.diary.content.replace(/\n/g, '<br/>')
    },
    
    wordCount() {
      if (!this.diary?.content) return 0
      return this.diary.content.replace(/\s/g, '').length
    }
  },
  onLoad(options) {
    this.diaryId = options.id
    this.initPage()
  },
  onShow() {
    // 如果从编辑页面返回，重新加载数据
    if (this.diary) {
      this.loadDiaryDetail()
    }
  },
  methods: {
    async initPage() {
      // 检查登录状态
      if (!this.userStore.checkLoginStatus()) return
      
      // 获取导航栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.navBarHeight = systemInfo.statusBarHeight + 44
      
      // 加载日记详情
      await this.loadDiaryDetail()
    },
    
    async loadDiaryDetail() {
      if (!this.diaryId) {
        uni.showToast({
          title: '参数错误',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        return
      }
      
      this.loading = true
      
      try {
        const res = await getDiaryDetailAPI(this.diaryId)
        this.diary = res.data
        
        // 设置导航栏标题
        uni.setNavigationBarTitle({
          title: this.diary.title || '日记详情'
        })
        
      } catch (error) {
        console.error('加载日记详情失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 获取心情表情
    getMoodEmoji(mood) {
      return this.moodEmojis[mood] || '😊'
    },
    
    // 格式化时间
    formatTime(datetime) {
      return formatDateTime(datetime, 'HH:mm')
    },
    
    // 图片预览
    previewImage(current) {
      const urls = this.diary.images.map(img => img.url)
      uni.previewImage({
        urls,
        current
      })
    },
    
    // 图片加载成功
    onImageLoad() {
      // 可以在这里处理图片加载成功的逻辑
    },
    
    // 图片加载失败
    onImageError() {
      console.warn('图片加载失败')
    },
    
    // 编辑日记
    editDiary() {
      if (!this.diary) return
      
      // 设置编辑状态
      this.diaryStore.setEditingDiary(this.diary.id)
      
      // 跳转到编辑页面
      uni.switchTab({
        url: '/pages/diary/edit'
      })
    },
    
    // 删除日记
    async deleteDiary() {
      try {
        await uni.showModal({
          title: '确认删除',
          content: `确定要删除日记"${this.diary.title}"吗？`,
          showCancel: true,
          confirmColor: '#ff4d4f'
        })
        
        this.loading = true
        
        await deleteDiaryAPI(this.diary.id)
        
        // 更新状态管理
        this.diaryStore.deleteDiary(this.diary.id)
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
        
      } catch (error) {
        if (error.errMsg !== 'showModal:fail cancel') {
          console.error('删除日记失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      } finally {
        this.loading = false
        this.showActionModal = false
      }
    },
    
    // 分享日记
    shareDiary() {
      // 构建分享内容
      const shareContent = {
        title: this.diary.title,
        desc: this.diary.content.substring(0, 100) + (this.diary.content.length > 100 ? '...' : ''),
        imageUrl: this.diary.images && this.diary.images.length > 0 ? this.diary.images[0].url : '',
        path: `/pages/diary/detail?id=${this.diary.id}`
      }
      
      // #ifdef MP-WEIXIN
      // 微信小程序分享
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
      // #endif
      
      // #ifdef APP-PLUS
      // APP端分享
      plus.share.sendWithSystem({
        type: 'text',
        content: `${shareContent.title}\n\n${shareContent.desc}`
      }, (res) => {
        console.log('分享成功:', res)
      }, (err) => {
        console.error('分享失败:', err)
      })
      // #endif
      
      // #ifdef H5
      // H5端分享（使用Web Share API或复制链接）
      if (navigator.share) {
        navigator.share({
          title: shareContent.title,
          text: shareContent.desc,
          url: window.location.href
        })
      } else {
        // 复制链接
        this.copyToClipboard(window.location.href)
        uni.showToast({
          title: '链接已复制',
          icon: 'success'
        })
      }
      // #endif
      
      this.showActionModal = false
    },
    
    // 复制到剪贴板
    copyToClipboard(text) {
      uni.setClipboardData({
        data: text,
        success: () => {
          uni.showToast({
            title: '复制成功',
            icon: 'success'
          })
        }
      })
    },
    
    // 返回
    goBack() {
      uni.navigateBack()
    }
  },
  
  // 微信小程序分享配置
  onShareAppMessage() {
    if (!this.diary) return {}
    
    return {
      title: this.diary.title,
      desc: this.diary.content.substring(0, 100),
      path: `/pages/diary/detail?id=${this.diary.id}`,
      imageUrl: this.diary.images && this.diary.images.length > 0 ? this.diary.images[0].url : ''
    }
  },
  
  onShareTimeline() {
    if (!this.diary) return {}
    
    return {
      title: `${this.diary.title} - 每日记`,
      query: `id=${this.diary.id}`,
      imageUrl: this.diary.images && this.diary.images.length > 0 ? this.diary.images[0].url : ''
    }
  }
}
</script>

<style scoped>
.detail-scroll {
  height: calc(100vh - 88px);
  padding-bottom: 40rpx;
}

.diary-header {
  padding: 40rpx 32rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.diary-title {
  font-size: 40rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.4;
  margin-bottom: 16rpx;
}

.diary-meta {
  display: flex;
  gap: 16rpx;
  align-items: center;
}

.meta-date {
  font-size: 28rpx;
  color: #666666;
}

.meta-time {
  font-size: 24rpx;
  color: #999999;
}

.diary-info {
  display: flex;
  gap: 32rpx;
  padding: 24rpx 32rpx;
  background-color: #fafafa;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.info-text {
  font-size: 26rpx;
  color: #666666;
}

.mood-emoji {
  font-size: 18rpx;
}

.diary-images {
  padding: 32rpx 32rpx 0;
}

.images-container {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.diary-image {
  width: 100%;
  border-radius: 12rpx;
  background-color: #f0f0f0;
}

.diary-content {
  padding: 32rpx;
}

.content-text {
  font-size: 32rpx;
  line-height: 1.8;
  color: #333333;
  word-break: break-word;
}

.diary-tags {
  padding: 0 32rpx 32rpx;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.tag {
  border-radius: 20rpx;
  padding: 12rpx 20rpx;
  font-size: 24rpx;
}

.tag-text {
  font-weight: 500;
}

.diary-stats {
  padding: 0 32rpx 32rpx;
  border-top: 1rpx solid #f0f0f0;
  padding-top: 32rpx;
}

.stats-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 16rpx;
}

.stats-item:last-child {
  margin-bottom: 0;
}

.stats-text {
  font-size: 24rpx;
  color: #999999;
}

.action-buttons {
  display: flex;
  gap: 24rpx;
  padding: 0 32rpx 40rpx;
}

.action-btn {
  flex: 1;
  height: 88rpx;
  border-radius: 44rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  font-size: 28rpx;
  border: none;
}

.action-btn::after {
  border: none;
}

.edit-btn {
  background-color: #e6f7ff;
  color: #1890ff;
}

.share-btn {
  background-color: #f6ffed;
  color: #52c41a;
}

.btn-text {
  font-size: 28rpx;
}
</style> 